<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2024/1/16
 * Time: 10:50
 */

namespace app\service;
use app\model\admin\Keyword AS model;
use app\model\admin\Config AS config;

class Keyword
{
    private $phone = 0;
    private $computer = 0;
    public function save(string $keyword) : string{
        $find = model::where('keyword',$keyword)->find();
        $data = [
            'start_time' => $this->last_month(),
            'end_time' => date('Y-m-d'),
        ];
        if (empty($find->keyword)){
            $find = model::create(array_merge(
                [
                    'keyword' => $keyword
                ],
                $data
            ));
        }else{
            $find->save($data);
        }
        $result = $this->search($keyword);
        if (!empty($result)) {
            $baidu = $result['baidu'];
            $zhanzhanggongju = $result['zhanzhanggongju'];
            $keywords = $zhanzhanggongju['keyword'] ?? [];
            //百度词条排序保存
//            $baidu['wordlist'] = json_decode(json_encode($result['wordlist']), true);
//            usort($baidu['wordlist'], function ($a, $b) {
//                return $b['pv'] - $a['pv']; // 倒序排列，所以使用减号
//            });
//            $keywords = array_column($baidu['wordlist'], 'word');
            if (empty($zhanzhanggongju['all']))$zhanzhanggongju['all'] = 0;
            if(!is_numeric($zhanzhanggongju['all']))$zhanzhanggongju['all'] = 0;
            foreach ($keywords AS $key => $value){
                if (strpos($value,$keyword) === false)unset($keywords[$key]);
            }

            if (count($keywords) > 10) {
                foreach ($keywords AS $key => $value){
                    $array[] = $value;
                    if (count($array) >= 10)break;
                }
                $keywords = $array;
            }
            $data = [
                'res_data' => $result,
                'zz_all' => (int)$zhanzhanggongju['pc'] + (int)$zhanzhanggongju['phone'],
                'zz_pc' => $zhanzhanggongju['pc'],
                'zz_phone' => $zhanzhanggongju['phone'],
                'all' => $baidu['number']->all->avg ?? 0,
                'pc' => $baidu['number']->pc->avg ?? 0,
                'phone' => $baidu['number']->wise->avg ?? 0,
                'keywords' => implode(',', $keywords)
            ];
            $pc_min_price = config::get_value('pc_min_price');
            $all_min_price = config::get_value('all_min_price');
            $phone_min_price = config::get_value('phone_min_price');
            //第一版算法
//            $data['pc_price'] = floor(ceil(($data['pc'] + 100) * (100 / $this->length($keyword))/100) * 100);
//            $data['phone_price'] = floor(ceil(($data['phone'] + 100) * (100 / $this->length($keyword)/100)) * 100);
//            $data['price'] = floor(ceil((0.8 * ($data['pc_price'] + $data['phone_price']))/100)*100);
            //第二版算法
//            $a = $this->pcphone($data['pc']);
//            $b = $this->pcphone($data['phone']);
//            $data['pc_price'] = bcmul(($data['pc'] + 100)  , $a,2);
//            $data['phone_price'] = bcmul(($data['phone'] + 100) , $b,2);
//            $data['price'] = floor(ceil((0.8 * ($data['pc_price'] + $data['phone_price']))/100)*100);
            //第三版算法
            $all = $data['all'] > $data['zz_all'] ? $data['all'] : $data['zz_all'];
            $a = $this->pcphone($all);
            $data['price'] =  ceil(bcmul(($all + 100)  , $a/100,0)) * 100;
            $data['pc_price'] =  floor(ceil($data['price']*0.65/100) * 100);
            $data['phone_price'] = floor(ceil($data['price']*0.75/100) * 100);


            $data['pc_price'] < $pc_min_price && $data['pc_price'] = $pc_min_price;
            $data['phone_price'] < $phone_min_price && $data['phone_price'] = $phone_min_price;
            $data['price'] < $all_min_price && $data['price'] = $all_min_price;
            $find->save($data);
            return 'OK';
        }else{
            return 'NO';
        }
    }

    public function pcphone($a){
        switch ($a){
            case $a = 0:
                $b = 20;
                break;
            case $a >= 1 && $a < 100:
                $b = 25;
                break;
            case $a >= 100 && $a < 200:
                $b = 27;
                break;
            case $a >= 200 && $a < 300:
                $b = 30;
                break;
            case $a >= 300 && $a < 500:
                $b = 33;
                break;
            case $a >= 500;
                $b = 33;
                break;
            default:
                $b = 33;
                break;
        }
        return $b;
    }

    public function search(string $keyword){
        try{
            $cookie = config::get_value('baidu_cookie');
            $cipherText = config::get_value('Cipher-Text');
            $keywords = new \app\service\Keyword();
            $baidu =  $keywords->baidu($keyword,$cookie,$cipherText);
            $cookie = config::get_value('zhanzhanggongju_cookie');
            $zhanzhanggongju =  $keywords->zhanzhanggongju($keyword,$cookie);
            return [
                'baidu' => $baidu,
                'zhanzhanggongju' => $zhanzhanggongju
            ];
        }catch (\Exception $e){
            return [
                'baidu' => (object)[
                    'all' => (object)['avg' => 0],
                    'pc' => (object)['avg' => 0],
                    'wise' => (object)['avg' => 0],
                ],
                'zhanzhanggongju' => []
            ];
        }
    }

    /**
     * 爬取百度指数数据
     * @param string $keyword
     * @param string $cookie
     * @return mixed
     */
    public function baidu(string $keyword, string $cookie,string $cipherText){
        $value = [
            [
                ["name" => $keyword,"wordType" => 1]
            ]
        ];
        $value = json_encode($value,JSON_UNESCAPED_SLASHES);
        $last_time = \app\model\Config::get_value('last_time');
        if($last_time == 1){
            $datetime = $this->last_month();
        }elseif($last_time == 2){
            $datetime = $this->last_three_month();
        }else{
            $datetime = $this->last_year();
        }
        $url = 'https://index.baidu.com/api/SearchApi/index?area=0&word='.$value.'&startDate='.$datetime.'&endDate='.date('Y-m-d');
        $array = [
            'Content-Type:application/json',
            'Cipher-Text:'.$cipherText,
            'Cookie:'.$cookie
        ];
        //百度指数数据查询
        // dd($array);
        $res = $this->curl($url,$array,false);
        $res = json_decode($res);
        if (empty($res->data->generalRatio))
            $data['number'] = (object)[
                'all' => (object)['avg' => 0],
                'pc' => (object)['avg' => 0],
                'wise' => (object)['avg' => 0],
            ];
        else
            $data['number'] = $res->data->generalRatio[0];
        //百度相关词条查询
//        $url = 'https://index.baidu.com/api/WordGraph/multi?wordlist[]='.$keyword;
//        $res = $this->curl($url,$array);
//        $res = json_decode($res);
//        $data['wordlist'] = $res->data->wordlist[0]->wordGraph;
        return $data;
    }

    public function zhanzhanggongju(string $keyword, string $cookie)
    {
        $url = 'https://rank.chinaz.com/ajaxsync.aspx?at=index';
        $html = $this->curl($url, [
                'user-agent:ApiPOST Runtime +https://www.apipost.cn',
                'Cookie:' . $cookie,
                'origin:https://rank.chinaz.com',
                'accept-encoding:gzip, deflate, br',
                'Referer:https://rank.chinaz.com/wordsindex.aspx',
                'Content-Type:application/x-www-form-urlencoded; charset=UTF-8'
        ], true, ['kw' => urlencode($keyword)]);
        while (strpos($html,'403') !== false){
            $html = $this->curl($url, [
                'user-agent:ApiPOST Runtime +https://www.apipost.cn',
                'Cookie:' . $cookie,
                'origin:https://rank.chinaz.com',
                'accept-encoding:gzip, deflate, br',
                'Referer:https://rank.chinaz.com/wordsindex.aspx',
                'Content-Type:application/x-www-form-urlencoded; charset=UTF-8'
            ], true, ['kw' => urlencode($keyword)]);
            sleep(1);
        }
        $pattern = '/mindex:\'(.*?)\'/';
        preg_match_all($pattern, $html, $mindex);
        $pattern = '/pcindex:\'(.*?)\'/';
        preg_match_all($pattern, $html, $pcindex);
        !empty($mindex[1]) && $this->phone = $mindex[1][0];
        !empty($pcindex[1]) && $this->computer = $pcindex[1][0];
        $url = 'https://data.chinaz.com/keyword/allindex/' . urlencode($keyword) .'/m-0';
        $array = [
            'Cookie:' . $cookie
        ];
        $html = $this->curl($url, $array, false);
        if (strpos($html,'抱歉，未找到相关的数据。') !== false) return [];
        // 使用正则表达式提取中间内容
        $pattern = '/<li class="col-220 z-tl nofoldtxt">(.*?)<\/li>/';
        $type = 1;
        preg_match_all($pattern, $html, $matches);
        if (empty($matches[1])){
            $type = 2;
            $pattern = '/<li class="w60 blue2 arow" style="overflow: hidden">(.*?)<\/li>/';
            preg_match_all($pattern, $html, $matches);
        }
        // 提取到的中间内容存储在$matches中
        if (!empty($matches[1])) {
            $html = implode(',',$matches[1]);
            $html = str_replace(['*','%','#','!','@','^','&','(',')'],'',$html);
            if($type == 1){
                $pattern = '/title="(.*?)"/';
                preg_match_all($pattern, $html, $matches);
                return ['pc' => $this->computer,'phone' => $this->phone,'keyword' => $matches[1]];
            }else{
                $html = str_replace(['<span style=\'color:red\'>','</span>'],['',''],$html);
                // dd(explode(',',$html));
                return ['pc' => $this->computer,'phone' => $this->phone,'keyword' => explode(',',$html)];
            }
        }else{
            return [];
        }
    }

    public function baiduc_(){
        $url = 'https://fengchao.baidu.com/hairuo/request.ajax?path=lightning%2FGET%2FKeywordSuggestService%2FgetKeywordRecommendPassive&reqid=4b534c48-c74d-4c35-fe9f-170848304240';
    }

    /**
     * curl POST
     * @param $url
     * @param $header
     * @return mixed
     */
    public function curl($url, $header,$is_post = true,$data = []){
        // $useragent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36';
        // 创建一个cURL资源
        $ch = curl_init();
        // 设置cURL选项
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, $is_post);
        curl_setopt($ch, CURLOPT_URL, $url);          // 设置目标网页的URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将返回的内容作为字符串返回，而不是直接输出
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//禁止 cURL 验证对等证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//是否检测服务器的域名与证书上的是否一致
        curl_setopt($ch, CURLOPT_ENCODING, "" );
        curl_setopt($ch, CURLOPT_AUTOREFERER, true );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5 );
        curl_setopt($ch, CURLOPT_TIMEOUT, 5 );
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5 );
        if(!empty($data)){
            $post = http_build_query($data);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        // curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
        // 执行cURL请求
        $response = curl_exec($ch);
        // 关闭cURL资源
        curl_close($ch);
        // 检查是否有错误发生
        if ($response === false) {
            //$error = curl_error($ch);
            die(json(['data' => [],'code' => 400,'msg' => '无法查询到数据']));
        } else {
            // 处理返回的内容
            return $response;
        }
    }

    /**
     * 取得上一个月的时间
     * @return string
     */
    public function last_month() : string{
        $currentDate = date('Y-m-d'); // 获取当前日期
        $lastMonth = date('Y-m-d', strtotime('-1 month', strtotime($currentDate))); // 获取上个月日期
        return (string)$lastMonth;
    }


    /**
     * 取得上三个月的时间
     * @return string
     */
    public function last_three_month() : string{
        $currentDate = date('Y-m-d'); // 获取当前日期
        $lastMonth = date('Y-m-d', strtotime('-3 month', strtotime($currentDate))); // 获取上个月日期
        return (string)$lastMonth;
    }

    /**
     * 取得前一年的时间
     * @return string
     */
    public function last_year() : string {
        $currentDate = date('Y-m-d'); // 获取当前日期
        $lastMonth = date('Y-m-d', strtotime('-1 year', strtotime($currentDate))); // 获取上个月日期
        return (string)$lastMonth;
    }

    /**
     * 解决汉字一个占三个字符串的问题
     * @param $string
     * @return int
     */
    public function length($string) : int{
        $pattern = '/[\x{4e00}-\x{9fa5}]/u'; // 匹配汉字的正则表达式
        preg_match_all($pattern, $string, $matches);
        $chineseChars = $matches[0];
        $number = count($chineseChars);
        return floor(strlen($string) - $number * 2);
    }
}